package au.id.wattle.chapman.j2as3;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Vector;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

public class J2AS3Task extends Task {
	private Vector<FileSet> filesets = new Vector<FileSet>();

	public void addFileset(FileSet fileset) {
		filesets.add(fileset);
	}

	private String location;

	public void setLocation(String location) {
		this.location = location;
	}

	protected void validate() {
		if (filesets.size() < 1)
			throw new BuildException("fileset not set");
	}

	public void execute() {
		validate();

		for (Iterator<FileSet> itFSets = filesets.iterator(); itFSets.hasNext();) {
			FileSet fs = (FileSet) itFSets.next();
			File baseDir = fs.getDir();
			DirectoryScanner ds = fs.getDirectoryScanner(getProject());
			String[] includedFiles = ds.getIncludedFiles();
			for (int i = 0; i < includedFiles.length; i++) {
				String filename = includedFiles[i];
				File inputFile = new File(baseDir.getPath(), filename);
				String as3file = filename.replaceAll("\\.java", ".as");
				File outputFile = new File(location, as3file);
				try {
					convertFile(inputFile, outputFile);
				} catch (IOException e) {
					throw new BuildException(e);
				}

			}
		}
	}

	private void convertFile(File file, File outputFile)
			throws java.io.IOException {
		String code;
		code = readFileAsString(file);
		code.replaceAll("\r", "");
		Converter converter = new Converter(code);
		String as3Code = converter.getNewClass();

		outputFile.getParentFile().mkdirs();
		outputFile.createNewFile();
		FileWriter writer = new FileWriter(outputFile);
		writer.write(as3Code);
		writer.close();
	}

	/**
	 * @param filePath
	 *            the name of the file to open. Not sure if it can accept URLs
	 *            or just filenames. Path handling could be better, and buffer
	 *            sizes are hardcoded
	 */
	private static String readFileAsString(File filePath)
			throws java.io.IOException {
		StringBuffer fileData = new StringBuffer(1000);
		BufferedReader reader = new BufferedReader(new FileReader(filePath));
		char[] buf = new char[1024];
		int numRead = 0;
		while ((numRead = reader.read(buf)) != -1) {
			String readData = String.valueOf(buf, 0, numRead);
			fileData.append(readData);
			buf = new char[1024];
		}
		reader.close();
		return fileData.toString();
	}

}
